# -*- coding: utf-8 -*-

from git import Repo
from com.maycur import config_loader
from com.maycur.git.base.git_operation import GitOperation
from conf.entity.module.git_config import GitConfig


class BranchPuller:
    git_config: GitConfig
    project_count: int

    def __init__(self):
        self.git_config = config_loader.get_git_config()
        self.project_count = 0
        for branch_pair in self.git_config.branch_pairs:
            self.project_count = self.project_count + len(branch_pair.projects)

    def re_pull(self):
        print(f'>>> there are {self.project_count} projects to handle <<<')

        for branch_pair in self.git_config.branch_pairs:
            print(f'\nstart processing branch pair: {branch_pair.pair_name} ...')
            print('------------------------------------------------------------------------')

            for project in branch_pair.projects:
                print(f'start processing project: {project.name} ...')
                repo = Repo(project.project_path)

                git_operation = GitOperation(repo, project)

                # delete local down_branch
                git_operation.delete_local_branch(branch_pair.down_branch)
                # delete local up_branch, in case of duplicate
                git_operation.delete_local_branch(branch_pair.up_branch)
                # fetch again
                git_operation.fetch_from_remote()
                # replace with up_branch
                git_operation.pull_from_remote(branch_pair.up_branch)
                print('re-pull from remote successfully')


if __name__ == '__main__':
    branch_puller = BranchPuller()
    branch_puller.re_pull()

